#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
from pathlib import Path
from typing import Optional

class Config:
    def __init__(self):
        self.config_dir = Path.home() / '.bbdown'
        self.config_file = self.config_dir / 'config.json'
        self.cookie_file = self.config_dir / 'cookie.txt'
        self.config_dir.mkdir(exist_ok=True)
        self.cookies = self._load_cookies()
    
    def _load_cookies(self) -> Optional[str]:
        """加载cookie"""
        if self.cookie_file.exists():
            with open(self.cookie_file, 'r', encoding='utf-8') as f:
                return f.read().strip()
        return None
    
    def save_cookies(self, cookies: str):
        """保存cookie"""
        with open(self.cookie_file, 'w', encoding='utf-8') as f:
            f.write(cookies.strip())
        self.cookies = cookies.strip()
    
    def get_cookies(self) -> Optional[str]:
        """获取cookie"""
        return self.cookies

    def _load_config(self):
        """加载配置文件"""
        if not self.config_dir.exists():
            self.config_dir.mkdir(parents=True)
        
        if self.config_file.exists():
            with open(self.config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                self.cookie = config.get('cookie')
    
    def save_config(self):
        """保存配置到文件"""
        config = {
            'cookie': self.cookie
        }
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=4, ensure_ascii=False)
    
    def set_cookie(self, cookie):
        """设置cookie"""
        self.cookie = cookie
        self.save_config()
    
    def get_cookie(self):
        """获取cookie"""
        return self.cookie 